//
//  FSTools.m
//  FSiOSClient
//
//  Created by purlible on 2024/8/23.
//

#import "FSTools.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import <Foundation/Foundation.h>
#import <CoreText/CoreText.h>
#import "AppDelegate.h"

@implementation FSTools

#pragma mark -----------------  基本类型判空  --------------------
#pragma mark --- 判断字符串是否为空
+ (BOOL)isStrEmpty:(NSString*)str
{
    if (str == nil || str == NULL||[str isEqual:@""])
    {
        return YES;
    }
    if ([str isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    return NO;
}
#pragma mark --- 判断字典是否为空
+(BOOL)isEmptyForDict:(NSDictionary*)dict
{
    if ( dict == nil ||[dict isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([dict isKindOfClass:[NSDictionary class]]) {
        if (dict.count==0) {
            return YES;
        }
    }
    return NO;
}
#pragma mark --- 判断数组是否为空
+(BOOL)isEmptyForArray:(NSArray*)array
{
    if ( array == nil ||[array isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([array isKindOfClass:[NSArray class]]) {
        if (array.count==0) {
            return YES;
        }
    }
    return NO;
}



#pragma mark ------------------ 用户信息校验 --------------------------
#pragma mark --- 判断手机号码格式是否正确
+ (BOOL)valiMobile:(NSString *)mobile
{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
        return NO;
    }else{
        NSString * firstStr = [mobile substringWithRange:NSMakeRange(0, 1)];
        if ([firstStr isEqualToString:@"1"]) {
            return YES;
        }else{
            return NO;
        }
        //        /**
        //         * 移动号段正则表达式
        //         */
        //        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        //        /**
        //         * 联通号段正则表达式
        //         */
        //        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        //        /**
        //         * 电信号段正则表达式
        //         */
        //        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        //        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        //        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        //        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        //        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        //        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        //        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        //
        //        if (isMatch1 || isMatch2 || isMatch3) {
        //            return YES;
        //        }else{
        //            return NO;
        //        }
        //        }
    }
}
#pragma mark --- 判断字符串是否是合法网址
+(BOOL)valiUrl:(NSString *)url
{
    NSString *regex =@"[a-zA-z]+://[^\\s]*";
    NSPredicate *urlPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [urlPredicate evaluateWithObject:url];
}
#pragma mark --- 判断字符串是否是纯数字字符
+(BOOL)isPureNumberCharacters:(NSString *)string
{
    string = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
    if(string.length > 0)
    {
        return NO;
    }
    return YES;
}

#pragma mark ------------------------------ 时间相关 ------------------------------
/*******************************************时间相关**********************************/

//时间戳
#pragma mark -   获取本地时间戳
+(NSString *)dateTime{
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%lld", (long long)[datenow timeIntervalSince1970]];
    return timeSp;
}
#pragma mark -  把服务器返回的时间yyyy-MM-dd HH:mm:ss 转为时间戳
+(NSString *)dateWithStringTotimestamp:(NSString *)timeStamp{
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd";
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];
    NSDate *date = [fmt dateFromString:timeStamp];
    NSString *timeSp = [NSString stringWithFormat:@"%lld", (long long)[date timeIntervalSince1970]];
    return timeSp;
}
#pragma mark -  字符串将时间转换成时间戳转
+(NSString *)dateWithString:(NSString *)timeStamp{
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm";
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];
    NSDate *date = [fmt dateFromString:timeStamp];
    NSString *timeSp = [NSString stringWithFormat:@"%lld", (long long)[date timeIntervalSince1970]];
    return timeSp;
}
#pragma mark -  将某个时间转化成 时间戳
+(NSInteger)timeSwitchTimestamp:(NSString *)formatTime andFormatter:(NSString *)format{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:format]; //(@"YYYY-MM-dd hh:mm:ss") ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate* date = [formatter dateFromString:formatTime]; //------------将字符串按formatter转成nsdate
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[date timeIntervalSince1970]] integerValue];
    return timeSp;
}
#pragma mark - 根据任意时间格式2016 - 4- 12 10:00 转化为13位时间戳
+(NSString *)dateAndTimeWithStringTotimestamp:(NSString *)timeStamp{
    
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm";
    fmt.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];
    NSDate *date = [fmt dateFromString:timeStamp];
    //13位时间戳
    NSString *timeSp = [NSString stringWithFormat:@"%lld000", (long long)[date timeIntervalSince1970]];
    return timeSp;
}
#pragma mark -  时间戳转为不同的格式
+(NSString *) dateToTime:(long long) timeStamp andforDate:(NSString  *) format
{
    NSString * time = [NSString stringWithFormat:@"%lld",timeStamp/1000];//13位转10位
    NSString *arg = time;
    if (![time isKindOfClass:[NSString class]]) {
        arg = [NSString stringWithFormat:@"%@", time];
    }
    
    NSTimeInterval timelong = ([arg doubleValue]);
    
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:timelong];
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:format];
    
    return [dateFormatter stringFromDate :date];
}
#pragma mark -- 获取当前时间戳对应的年月日且为int类型 2017年5月1日
+ (NSString *)getNowTimeForYearMonthDay
{
    //获取当前时间
    NSDate *now = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ;
    NSDateComponents * dateComponent = [calendar components:unitFlags fromDate:now];
    NSInteger year = [dateComponent year];
    NSInteger month = [dateComponent month];
    NSInteger day = [dateComponent day];
    NSString * nowDayString = [NSString stringWithFormat:@"%ld年%ld月%ld日",(long)year,(long)month,(long)day];
    return nowDayString;
}

#pragma mark -  获取当前时间转化为不同的格式的时间
+(NSString *)getNow:(NSString *) format
{
    NSDate *date=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:format];
    NSString *nowStr=[dateformatter stringFromDate:date];
    return nowStr;
}
#pragma mark -- 根据时间戳获取月、日、时间
+ (NSString *)getMonthDayAndTimeFromTimeSp:(long long)timeSp
{
    NSInteger  month = [[FSTools dateToTime:timeSp andforDate:@"MM"] integerValue];
    NSInteger  day= [[FSTools dateToTime:timeSp andforDate:@"dd"] integerValue];
    NSString * time = [FSTools dateToTime:timeSp andforDate:@"HH:mm"];
    
    NSString * transitionTime = [NSString stringWithFormat:@"%ld月%ld日  %@",(long)month,(long)day,time];
    //    NSString * currentMonthDay = [FSTools getNow:@"MM.dd"];
    //    NSString * monthDay = [NSString stringWithFormat:@"%@.%@",[FSTools dateToTime:timeSp andforDate:@"MM"],[FSTools dateToTime:timeSp andforDate:@"dd"]];
    //    if ([currentMonthDay isEqualToString:monthDay]) {
    //        transitionTime = [NSString stringWithFormat:@"今天  %@",time];
    //    }
    return transitionTime;
}
//周几
#pragma mark -   把时间转为周几
+ (NSString*)weekdayStringFromDate:(NSString*)time
{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:@"yyyyMMdd"];//设定时间格式,要注意跟下面的dateString匹配，否则日起将无效
    NSDate *inputDate =[dateFormat dateFromString:time];
    if (inputDate == nil) {
        return @"";
    }
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}
#pragma mark -   把时间转为周几
+ (NSString*)getWeekdayStringFromDate:(NSString*)time
{
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    [dateFormat setDateFormat:@"yyyyMMdd"];//设定时间格式,要注意跟下面的dateString匹配，否则日起将无效
    NSDate *inputDate =[dateFormat dateFromString:time];
    if (inputDate == nil) {
        return @"";
    }
    NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    
    [calendar setTimeZone: timeZone];
    
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    
    return [weekdays objectAtIndex:theComponents.weekday];
    
}

#pragma mark -- 获取当前是周几
+ (NSInteger )getNowWeekday
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDate *now = [NSDate date];
    // 话说在真机上需要设置区域，才能正确获取本地日期，天朝代码:zh_CN
    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    comps = [calendar components:unitFlags fromDate:now];
    
    return [comps weekday];
}

#pragma mark --- 将0-6 转换成周日 到 周六
+ (NSString *)fromIntegerToWeekString:(NSInteger)integer
{
    NSString * weekString;
    switch (integer) {
        case 0:
            weekString = @"周日";
            break;
        case 1:
            weekString = @"周一";
            break;
        case 2:
            weekString = @"周二";
            break;
        case 3:
            weekString = @"周三";
            break;
        case 4:
            weekString = @"周四";
            break;
        case 5:
            weekString = @"周五";
            break;
        case 6:
            weekString = @"周六";
            break;
        default:
            break;
    }
    return weekString;
}
#pragma mark --- 将周日 到 周六 转换成 0 - 6
+ (NSInteger )fromWeekStringToInteger:(NSString *)weekString
{
    NSInteger  weekValue;
    if ([weekString isEqualToString:@"周日"]) {
        weekValue = 0;
    }else if ([weekString isEqualToString:@"周一"]) {
        weekValue = 1;
    }else if ([weekString isEqualToString:@"周二"]) {
        weekValue = 2;
    }else if ([weekString isEqualToString:@"周三"]) {
        weekValue = 3;
    }else if ([weekString isEqualToString:@"周四"]) {
        weekValue = 4;
    }else if ([weekString isEqualToString:@"周五"]) {
        weekValue = 5;
    }else {
        weekValue = 6;
    }
    return weekValue;
}

//时间比较
#pragma mark -- 判断字符串是否大于当前时间
+(BOOL )isGreaterThanCurrentTimeWithTimeString:(NSString *)string
{
    NSInteger selectTimeSp = [FSTools timeSwitchTimestamp:string andFormatter:@"yyyy-MM-dd HH:mm"] ;
    NSInteger currentTimeSp = [[NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]] integerValue];
    return selectTimeSp+60>currentTimeSp;
}
#pragma mark -- 计算2个日期相差天数
+(NSInteger)daysFromDate:(NSDate *)startDate toDate:(NSDate *)endDate {
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    // 话说在真机上需要设置区域，才能正确获取本地日期，天朝代码:zh_CN
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //得到相差秒数
    NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
    int days = ((int)time)/(3600*24);
    int hours = ((int)time)%(3600*24)/3600;
    int minute = ((int)time)%(3600*24)/3600/60;
    if (days <= 0 && hours <= 0&&minute<= 0) {
        NSLog(@"0天0小时0分钟");
        return 0;
    }
    else {
        NSLog(@"%@",[[NSString alloc] initWithFormat:@"%i天%i小时%i分钟",days,hours,minute]);
        // 之所以要 + 1，是因为 此处的days 计算的结果 不包含当天 和 最后一天\
        （如周一 和 周四，计算机 算的结果就是2天（周二和周三），日常算，周一——周四相差3天，所以需要+1）\
        对于时分 没有进行计算 可以忽略不计
        return days + 1;
    }
}
#pragma mark --获取未来某个日期是周几
/**
 *  获取未来某个日期是周几
 *  注意：featureDate 传递过来的格式 必须 和 formatter.dateFormat 一致，否则endDate可能为nil
 *
 */
+ (NSString *)featureWeekdayWithDate:(NSString *)featureDate{
    // 创建 格式 对象
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // 设置 日期 格式 可以根据自己的需求 随时调整， 否则计算的结果可能为 nil
    formatter.dateFormat = @"yyyy-MM-dd";
    // 将字符串日期 转换为 NSDate 类型
    NSDate *endDate = [formatter dateFromString:featureDate];
    // 判断当前日期 和 未来某个时刻日期 相差的天数
    long days = [self daysFromDate:[NSDate date] toDate:endDate];
    // 将总天数 换算为 以 周 计算（假如 相差10天，其实就是等于 相差 1周零3天，只需要取3天，更加方便计算）
    NSInteger day = days >= 7 ? days % 7 : days;
    NSInteger week = [FSTools getNowWeekday] + day;
    switch (week) {
        case 1:
            return @"周日";
            break;
        case 2:
            return @"周一";
            break;
        case 3:
            return @"周二";
            break;
        case 4:
            return @"周三";
            break;
        case 5:
            return @"周四";
            break;
        case 6:
            return @"周五";
            break;
        case 7:
            return @"周六";
            break;
            
        default:
            break;
    }
    return nil;
}
#pragma mark -- 判断日期是否在本周 当天为今天 本周为8月28日 周一 其他为 7月26日
+ (NSString *)getDateStringFromDate:(NSDate *)date
{
    //传入日期处理
    NSCalendar * targetCalendar = [NSCalendar currentCalendar];
    NSDateComponents * targetComp = [targetCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | kCFCalendarUnitWeekOfMonth fromDate:date];
    //当天日期处理
    NSDate *now = [NSDate date];
    NSCalendar * nowCalendar = [NSCalendar currentCalendar];
    NSDateComponents *nowComp = [nowCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | kCFCalendarUnitWeekOfMonth fromDate:now];
    
    //同一天
    if (targetComp.year == nowComp.year && targetComp.month == nowComp.month && targetComp.day == nowComp.day) {
        return [NSString stringWithFormat:@"%ld月%ld日 今天",(long)targetComp.month,(long)targetComp.day];
    }
    NSLog(@"targetComp 该月第%ld周",(long)targetComp.weekOfMonth);
    NSLog(@"nowComp 该月第%ld周",(long)nowComp.weekOfMonth);
    
    //同一周
    if (targetComp.year == nowComp.year && targetComp.month == nowComp.month && targetComp.weekOfMonth == nowComp.weekOfMonth) {
        NSString * weekStr = [FSTools fromIntegerToWeekString:targetComp.weekday-1];
        NSString * timeStr = [NSString stringWithFormat:@"%ld月%ld日 %@",(long)targetComp.month,(long)targetComp.day,weekStr];
        return timeStr;
    }
    //其他日期
    NSString * timeStr = [NSString stringWithFormat:@"%ld月%ld日",(long)targetComp.month,(long)targetComp.day];
    return timeStr;
}
#pragma mark -- 获取动态时间(当天显示 今天 其余显示月日时间)
+ (NSString *)getDynamicDateStringFromTimeSp:(long long)timeSp
{
    NSString * time = [NSString stringWithFormat:@"%lld",timeSp/1000];//13位转10位
    NSString *arg = time;
    if (![time isKindOfClass:[NSString class]]) {
        arg = [NSString stringWithFormat:@"%@", time];
    }
    
    NSTimeInterval timelong = ([arg doubleValue]);
    
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:timelong];
    //传入日期处理
    NSCalendar * targetCalendar = [NSCalendar currentCalendar];
    NSDateComponents * targetComp = [targetCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | kCFCalendarUnitWeekOfMonth fromDate:date];
    
    //当天日期处理
    NSDate *now = [NSDate date];
    NSCalendar * nowCalendar = [NSCalendar currentCalendar];
    NSDateComponents *nowComp = [nowCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | kCFCalendarUnitWeekOfMonth fromDate:now];
    
    NSString * dateString;
    //同一天
    if (targetComp.year == nowComp.year && targetComp.month == nowComp.month && targetComp.day == nowComp.day) {
        dateString = @"今天";
    }else{
        dateString = [NSString stringWithFormat:@"%ld月%ld日",(long)targetComp.month,(long)targetComp.day];
    }
    NSString * timeStr = [NSString stringWithFormat:@"%@ %@",dateString,[FSTools dateToTime:timeSp andforDate:@"HH:mm"]];
    return timeStr;
}

#pragma mark -- 时间戳对应的年月日且为int类型 2017年5月1日 18:22 当天时间显示为今天
+ (NSString *)getDynamicDetailTimeFromTimeSp:(long long)timeSp
{
    NSString * time = [NSString stringWithFormat:@"%lld",timeSp/1000];//13位转10位
    NSString *arg = time;
    if (![time isKindOfClass:[NSString class]]) {
        arg = [NSString stringWithFormat:@"%@", time];
    }
    
    NSTimeInterval timelong = ([arg doubleValue]);
    
    NSDate *date=[NSDate dateWithTimeIntervalSince1970:timelong];
    //传入日期处理
    NSCalendar * targetCalendar = [NSCalendar currentCalendar];
    NSDateComponents * targetComp = [targetCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | kCFCalendarUnitWeekOfMonth fromDate:date];
    
    //当天日期处理
    NSDate *now = [NSDate date];
    NSCalendar * nowCalendar = [NSCalendar currentCalendar];
    NSDateComponents *nowComp = [nowCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday | kCFCalendarUnitWeekOfMonth fromDate:now];
    
    NSString * dateString;
    //同一天
    if (targetComp.year == nowComp.year && targetComp.month == nowComp.month && targetComp.day == nowComp.day) {
        dateString = @"今天";
    }else{
        dateString = [NSString stringWithFormat:@"%ld年%ld月%ld日",(long)targetComp.year,(long)targetComp.month,(long)targetComp.day];
    }
    NSString * timeStr = [NSString stringWithFormat:@"%@ %@",dateString,[FSTools dateToTime:timeSp andforDate:@"HH:mm"]];
    return timeStr;
}


#pragma mark - ----------------- 数据格式校验 --------------------------
#pragma mark --- 检测输入表情
+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}
#pragma mark --- 检测输入中文
+(BOOL)stringTextingChinese:(NSString*)string
{
    NSString * regex = @"^[\u4E00-\u9FA5]*$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}
#pragma mark --- 检测输入数字
+(BOOL)stringTextingNumber:(NSString*)string
{
    NSString * regex = @"^[0-9]{0,20}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}
#pragma mark --- 检测输入中文和表情
+(BOOL)stringTestingChineseandSymbol:(NSString*)string
{
    NSString * regex = @"^[A-Za-z0-9]{0,25}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}
#pragma mark --- 检测输入6~12为数字和字母
+(BOOL)stringTextingSixUntilTwelve:(NSString*)string
{
    //    NSString * regex  = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$";//6到12数字和字母
    NSString * regex  = @"^[0-9a-zA-z]{6,12}$";//6到12数字或字母
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}
#pragma mark --- 检测输入0~12为数字和字母
+(BOOL)stringTextingZeroUntilTwelve:(NSString*)string
{
    NSString * regex = @"^[0-9A-Za-z]{0,12}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}
#pragma mark --- 检测输入0~20位数字和字母
+(BOOL)stringTextingZeroUntilTwenty:(NSString*)string
{
    NSString * regex = @"^[0-9A-Za-z]{0,20}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}
#pragma mark --- 检测输入0~12位数字
+(BOOL)stringTextingZeroUntilTwelveNumber:(NSString*)string
{
    NSString * regex = @"^{0,12}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}



#pragma mark - ----------------- 格式处理 --------------------------
#pragma mark --- 判空后返回字符串
+(NSString *)judgeStr:(NSString *) str
{
    return [self isStrEmpty:str]?@"":str;
}
#pragma mark --- 截取字符串长度
+(NSString *) subStringWithLength:(NSString *)text strLength:(NSInteger)len
{
    if (text.length>len) {
        NSMutableString *textStr = [NSMutableString stringWithFormat:@"%@",text];
        NSString *textLen = [NSString stringWithFormat:@"%@...",[textStr substringToIndex:len]];
        return textLen;
    }else{
        return text;
    }
}
#pragma mark --- 把毫秒秒转化为 3.02
+(NSString *)convertSecondToDataFormat:(NSString *) time
{
    // 小时 18:03:04
    double timeDouble = [time doubleValue];
    int intTime = [time intValue];
    int hour    = intTime/3600;
    int minutes = intTime%3600/60;
    double dian = (intTime%3600%60 + (timeDouble - intTime))/100;
    NSString *sv = [NSString stringWithFormat:@"%.2f",round(dian*100)/100];
    NSArray *array = [sv componentsSeparatedByString:@"."]; //从字符A中分隔成2个元素的数组
    NSString * timeStr = @"";
    if (hour == 0) {
        if (minutes == 0) {
            timeStr = sv;
        }else{
            timeStr = [NSString stringWithFormat:@"%d:%@",minutes,array[1]];
        }
    }else{
        timeStr = [NSString stringWithFormat:@"%d:%02d:%@",hour,minutes,array[1]];
    }
    return timeStr;
}
#pragma mark --- 中文汉化
+ (NSString *)strUTF8Encoding:(NSString *)str
{
    return [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
}

#pragma mark --- 对象转JSONString
+ (NSString *)objectToJsonString:(id)object{
    NSData *data=[NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    return jsonStr;
}

#pragma mark ---  字典转json字符串方法
// 去除空格和换行符
+ (NSString *)convertToJsonData:(id)object
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    //去掉字符串中的空格
    NSRange range = {0,jsonString.length};
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    //去掉字符串中的换行符
    NSRange range2 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    //将:换成=
    NSRange range3 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@":" withString:@"=" options:NSLiteralSearch range:range3];
    //将[换成(
    NSRange range4 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"[" withString:@"(" options:NSLiteralSearch range:range4];
    //将]换成)
    NSRange range5 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"]" withString:@")" options:NSLiteralSearch range:range5];
    return mutStr;
    
}

/**
 十进制转换十六进制
 
 @param decimal 十进制数
 @return 十六进制数
 */
+ (NSString *)getHexByDecimal:(NSInteger)decimal {
    
    NSString *hex =@"";
    NSString *letter;
    NSInteger number;
    for (int i = 0; i<9; i++) {
        
        number = decimal % 16;
        decimal = decimal / 16;
        switch (number) {
                
            case 10:
                letter =@"A"; break;
            case 11:
                letter =@"B"; break;
            case 12:
                letter =@"C"; break;
            case 13:
                letter =@"D"; break;
            case 14:
                letter =@"E"; break;
            case 15:
                letter =@"F"; break;
            default:
                letter = [NSString stringWithFormat:@"%ld", (long)number];
        }
        hex = [letter stringByAppendingString:hex];
        if (decimal == 0) {
            break;
        }
    }
    if (hex.length == 1) {
        hex = [@"0" stringByAppendingString:hex];
    }
    return hex;
}


#pragma mark --- 特殊字符检测
-(BOOL)isIncludeSpecialCharact: (NSString *)str {
    //***需要过滤的特殊字符：~￥#&*<>《》()[]{}【】^@/￡¤￥|§¨「」『』￠￢￣~@#￥&*（）——+|《》$_€。
    NSRange urgentRange = [str rangeOfCharacterFromSet: [NSCharacterSet characterSetWithCharactersInString: @"~￥#&*<>《》()[]{}【】^@/￡¤￥|§¨「」『』￠￢￣~@#￥&*（）——+|《》$_€"]];
    if (urgentRange.location == NSNotFound)
    {
        return NO;
    }
    return YES;
}


#pragma mark --- 检测手机号
+(BOOL)stringTextingPhoneNumber:(NSString*)string{
    NSString * regex = @"^1(2[0-9]|3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\\d{8}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:string];
    return isMatch;
}










/*********************************************其它**********************************/
#pragma mark -- 获取label 的分割点 (将lable分行)
+ (NSArray *)getSeparatedLinesFromLabel:(UILabel *)label
{
    NSString *text = [label text];
    UIFont   *font = [label font];
    CGRect    rect = [label frame];
    
    CTFontRef myFont = CTFontCreateWithName((__bridge CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)myFont range:NSMakeRange(0, attStr.length)];
    
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString((__bridge CFAttributedStringRef)attStr);
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));
    
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    
    NSArray *lines = (__bridge NSArray *)CTFrameGetLines(frame);
    return lines;
}

#pragma mark -- 根据lable返回lable的行数和每行字数
+ (NSArray *)getLinesArrayOfStringInLabel:(UILabel *)label{
    NSString *text = [label text];
    UIFont *font = [label font];
    CGRect rect = [label frame];
    
    CTFontRef myFont = CTFontCreateWithName(( CFStringRef)([font fontName]), [font pointSize], NULL);
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    [attStr addAttribute:(NSString *)kCTFontAttributeName value:(__bridge  id)myFont range:NSMakeRange(0, attStr.length)];
    CFRelease(myFont);
    CTFramesetterRef frameSetter = CTFramesetterCreateWithAttributedString(( CFAttributedStringRef)attStr);
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, CGRectMake(0,0,rect.size.width,100000));
    CTFrameRef frame = CTFramesetterCreateFrame(frameSetter, CFRangeMake(0, 0), path, NULL);
    NSArray *lines = ( NSArray *)CTFrameGetLines(frame);
    NSMutableArray *linesArray = [[NSMutableArray alloc]init];
    for (id line in lines) {
        CTLineRef lineRef = (__bridge  CTLineRef )line;
        CFRange lineRange = CTLineGetStringRange(lineRef);
        NSRange range = NSMakeRange(lineRange.location, lineRange.length);
        NSString *lineString = [text substringWithRange:range];
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithFloat:0.0]));
        CFAttributedStringSetAttribute((CFMutableAttributedStringRef)attStr, lineRange, kCTKernAttributeName, (CFTypeRef)([NSNumber numberWithInt:0.0]));
        //NSLog(@"''''''''''''''''''%@",lineString);
        [linesArray addObject:lineString];
    }
    
    CGPathRelease(path);
    CFRelease( frame );
    CFRelease(frameSetter);
    return (NSArray *)linesArray;
}




/*********************************************蓝牙数据 NSString 和 Data 转换**********************************/
#pragma mark -- 将 NSString 16 进制 字符串 转化为   NSData @"0a1234 0b23454" -->  <0a1234 0b23454>
+(NSData*)stringToByte:(NSString*)string
{
    NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([hexString length]%2!=0) {
        return nil;
    }
    Byte tempbyt[1]={0};
    NSMutableData* bytes=[NSMutableData data];
    for(int i=0;i<[hexString length];i++)
    {
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)
        int int_ch1;
        if(hex_char1 >= '0' && hex_char1 <='9')
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48
        else if(hex_char1 >= 'A' && hex_char1 <='F')
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65
        else if(hex_char1 == '{')
            int_ch1 = 123; //// { 的Ascll - 123
        else if(hex_char1 == '}')
            int_ch1 = 125; //// } 的Ascll - 125
        else
            return nil;
        i++;
        
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)
        int int_ch2;
        if(hex_char2 >= '0' && hex_char2 <='9')
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48
        else if(hex_char2 >= 'A' && hex_char2 <='F')
            int_ch2 = hex_char2-55; //// A 的Ascll - 65
        else if(hex_char2 == '{')
            int_ch2 = 123; //// { 的Ascll - 123
        else if(hex_char2 == '}')
            int_ch2 = 125; //// } 的Ascll - 125
        else
            return nil;
        
        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里
        [bytes appendBytes:tempbyt length:1];
    }
    return bytes;
}



#pragma mark --  将 16 进制 NSData 转化为 NSString 字符串  <0a1234 0b23454> --> @"0a1234 0b23454"

+(NSString*)coverFromHexDataToStr:(NSData*)hexData
{
    const unsigned char* dataBuffer = (const unsigned char*)[hexData bytes];
    
    if(!dataBuffer){
        
        return nil;
        
    }
    
    NSUInteger dataLength = [hexData length];
    
    NSMutableString* hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
    
    for(int i = 0; i < dataLength; i++){
        
        [hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
        
    }
    
    NSString * result = [NSString stringWithString:hexString];
    
    return result;
}





#pragma mark -- demo
//将16进制的字符串转换成NSData
+ (NSData *)convertHexStrToData:(NSString *)str
{
    if (!str.length) {
        return nil;
    }
    
    NSMutableData *tempData = [NSMutableData dataWithCapacity:10];
    NSRange range;
    if ([str length] %2 == 0) {
        range = NSMakeRange(0,2);
    } else {
        range = NSMakeRange(0,1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [tempData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    
    return [NSData dataWithData:tempData];
}

//将NSData转为16进制的字符串
+ (NSString *)convertDataToHexStr:(NSData *)data
{
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *tempString = [NSMutableString stringWithCapacity:data.length];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange,BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i =0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) &0xff];
            if ([hexStr length] == 2) {
                [tempString appendString:hexStr];
            }
            else {
                [tempString appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return [NSString stringWithString:tempString];
}
//十进制准换为十六进制字符串
+ (NSString *)hexStringFromString:(NSString *)string
{
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte转换为16进制。
    NSString *hexStr=@"";
    for(int i=0;i<[myD length];i++){
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if([newHexStr length]==1)
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        else
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
    }
    return hexStr;
}

+(NSString *) parseByteArray2HexString:(Byte[]) bytes
{
    NSMutableString *hexStr = [[NSMutableString alloc]init];
    int i = 0;
    if(bytes){
        while (bytes[i] != '\0'){
            NSString *hexByte = [NSString stringWithFormat:@"%x",bytes[i] & 0xff];///16进制数
            if([hexByte length]==1)
                [hexStr appendFormat:@"0%@", hexByte];
            else
                [hexStr appendFormat:@"%@", hexByte];
            i++;
        }
    }
    return hexStr;
}



+(NSString *)stringFromHexString:(NSString *)hexString
{//
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 +1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i =0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner * scanner = [[NSScanner alloc] initWithString:hexCharStr] ;
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    return unicodeString;
}

//10进制转16进制
+(NSString *)ToHex:(long long int)tmpid
{
    NSString *nLetterValue;
    NSString *str =@"";
    long long int ttmpig;
    for (int i =0; i<9; i++) {
        ttmpig=tmpid%16;
        tmpid=tmpid/16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue =@"A";break;
            case 11:
                nLetterValue =@"B";break;
            case 12:
                nLetterValue =@"C";break;
            case 13:
                nLetterValue =@"D";break;
            case 14:
                nLetterValue =@"E";break;
            case 15:
                nLetterValue =@"F";break;
            default:nLetterValue=[[NSString alloc]initWithFormat:@"%lli",ttmpig];
                
        }
        str = [nLetterValue stringByAppendingString:str];
        if (tmpid == 0) {
            break;
        }
        
    }
    return str;
}



//十六进制转换为普通字符串的。
+ (NSString *)ConvertHexStringToString:(NSString *)hexString {
    
    char *myBuffer = (char *)malloc((int)[hexString length] / 2 + 1);
    bzero(myBuffer, [hexString length] / 2 + 1);
    for (int i = 0; i < [hexString length] - 1; i += 2) {
        unsigned int anInt;
        NSString * hexCharStr = [hexString substringWithRange:NSMakeRange(i, 2)];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        [scanner scanHexInt:&anInt];
        myBuffer[i / 2] = (char)anInt;
    }
    NSString *unicodeString = [NSString stringWithCString:myBuffer encoding:4];
    //    BabyLog(@"===字符串===%@",unicodeString);
    return unicodeString;
}

//普通字符串转换为十六进制
+ (NSString *)ConvertStringToHexString:(NSString *)string {
    NSData *myD = [string dataUsingEncoding:NSUTF8StringEncoding];
    Byte *bytes = (Byte *)[myD bytes];
    //下面是Byte 转换为16进制。
    NSString *hexStr=@"";
    for (int i=0;i<[myD length];i++) {
        NSString *newHexStr = [NSString stringWithFormat:@"%x",bytes[i]&0xff];///16进制数
        
        if ([newHexStr length]==1) {
            hexStr = [NSString stringWithFormat:@"%@0%@",hexStr,newHexStr];
        }
        else{
            hexStr = [NSString stringWithFormat:@"%@%@",hexStr,newHexStr];
        }
        
    }
    return hexStr;
}


//int转data
+ (NSData *)ConvertIntToData:(int)i {
    
    NSData *data = [NSData dataWithBytes: &i length: sizeof(i)];
    return data;
}

//data转int
+ (int)ConvertDataToInt:(NSData *)data {
    int i;
    [data getBytes:&i length:sizeof(i)];
    return i;
}

//十六进制转换为普通字符串的。
+ (NSData *)ConvertHexStringToData:(NSString *)hexString {
    
    NSData *data = [[self ConvertHexStringToString:hexString] dataUsingEncoding:NSUTF8StringEncoding];
    return data;
}


+ (void)copySandboxFile:(NSString *)filePath completion:(void(^)(BOOL success,NSString *destinationPath))completion
{
    BOOL success=YES;
    
    NSFileManager *fileManager=[NSFileManager defaultManager];
    
    NSString *libraryPath=NSTemporaryDirectory();
    
    NSString *googleMapWebPath=[libraryPath stringByAppendingPathComponent:@"dist"];
    
    static BOOL hasCopy=NO;
    
    if (!hasCopy||![fileManager fileExistsAtPath:googleMapWebPath isDirectory:nil])
    {
        if ([fileManager fileExistsAtPath:googleMapWebPath isDirectory:nil])//文件存在 删除
        {
            [fileManager removeItemAtPath:googleMapWebPath error:nil];
        }
        
        if (![fileManager fileExistsAtPath:googleMapWebPath isDirectory:nil])//文件不存在
        {
            NSError *error;
            
            success=success&&[fileManager copyItemAtPath:filePath toPath:googleMapWebPath error:&error];
        }
        
        hasCopy=success;
    }
    
    if (completion)
    {
        completion(success,libraryPath);
    }
}

+ (BOOL)isCurrentLanguageSimplifiedChinese
{
    NSArray<NSString *> *preferredLanguages = [NSLocale preferredLanguages];
    NSString *currentLanguage = preferredLanguages.firstObject;
    
    if ([currentLanguage hasPrefix:@"zh-Hans"]) {
        return YES;
    } else {
        return NO;
    }
}

@end
